package cn.dduan.fool.thread.pool.executor;

import cn.dduan.fool.thread.pool.task.MyCallable;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.*;

/**
 * ThreadPoolExecutor() 创建线程池-推荐
 *
 * @author dduan
 * @version 1.0
 * @date 2023/3/19
 */
@Slf4j
public class MyThreadPoolExecutor {
    // 线程池中的核心线程数
    private static final int CORE_POOL_SIZE = 5;
    // 线程池中最大线程数
    private static final int MAX_POOL_SIZE = 10;
    // 闲置超时时间
    private static final Long KEEP_ALIVE_TIME = 1L;
    // 线程池中的任务队列
    private static final int QUEUE_SIZE = 100;

    public void execTask() {
        ThreadPoolExecutor executor = new ThreadPoolExecutor(CORE_POOL_SIZE,
                MAX_POOL_SIZE,
                KEEP_ALIVE_TIME,
                TimeUnit.MILLISECONDS,
                new ArrayBlockingQueue<>(QUEUE_SIZE),
                new ThreadFactory() {
                    @Override
                    public Thread newThread(Runnable r) {
                        return new Thread(r, Thread.currentThread().getName());
                    }
                },
                new ThreadPoolExecutor.CallerRunsPolicy());

        // 任务返回值
        List<Future<String>> futureList = new ArrayList<>();

        for (int i = 0; i < 20; i++) {
            // 执行Runnable任务
            // executor.execute(new MyRunnable(i));
            // 执行Callable任务
            Future<String> future = executor.submit(new MyCallable());
            futureList.add(future);
        }
        for (Future<String> future : futureList) {
            try {
                log.info("{} : {}", new Date(), future.get());
            } catch (InterruptedException | ExecutionException e) {
                e.printStackTrace();
            }
        }
        // 终止线程池
        executor.shutdown();
        log.info("线程池终止状态：{}", executor.isShutdown());
    }

    public static void main(String[] args) {
        MyThreadPoolExecutor t = new MyThreadPoolExecutor();
        t.execTask();

        for (int i = 0; i < 5; i++) {
            log.info("{}-{}", Thread.currentThread().getName(), i);
        }
    }
}
